import * as React from 'react';
import Header from '@/commonComponents/header/Header';
import useAuth from '@/utils/hooks/useAuth';
import { useSearchParams } from 'react-router-dom';
import nowTime from '@/utils/nowTime';
import SocketContext, { mySocket } from './socketContext';
import ChatBox from './components/chatBox/customer';
import ServiceChatBox from './components/chatBox/service';
import Bottom from './components/bottom/customer';
import { initSender, senderType, initRevicer, revicerType } from './types';
import { toBottom, sendImage } from './common';
import { getToken } from '@/utils/localStorge';
// import notLoginPng from '@/imgs/not_login.png';
import NoLogin from '@/commonComponents/noLogin/index';
import './index.module.scss';

const { memo, useState, useEffect, useRef } = React;

interface ConversitionType {
  SendId?: number;
  ReviceId?: number;
  Content: string;
  Identity: number;
  Type: number;
  // 在线或者不在线，1不在线，0在线
  State?: number;
  timeStmp?: string;
  socketId?: number;
  CreateDateUtc?: Date;
  Title?: null | string;
  Description?: null | string;
  Label?: null | string;
  Thumbnail?: null | string;
  NoSend?: boolean;
}
function Services() {
  const { back } = useAuth();
  const [conversition, setConversition] = useState<ConversitionType[]>([
    {
      Type: 0,
      Identity: 2,
      Content: `亲，下拉可查看历史聊天消息哦～若您需咨询问题，建议您点击【订单】，选择需咨询的订单点击【发送订单】`,
    },
  ]);
  const [params] = useSearchParams();
  const isService = params.get('sendId');
  // const $socket: any = useContext('$socket');
  // 发送者对象
  const [sender, setSender] = useState<senderType>(initSender);
  // 接收者对象
  const [revicer, setRevicer] = useState<revicerType>(initRevicer);
  const [sendInfo, setSendInfo] = useState('');
  const chatRef = useRef();

  useEffect(() => {
    joinChat();
    joinSuccess();
    joinError();
    // 接收信息
    mySocket.on('reviceMsg', reviceMsg);
    return () => {
      mySocket.off('reviceMsg');
    };
  }, []);

  function reviceMsg(data: any) {
    // 接收信息
    // if (sender.isService && data.ReviceId === sender.id) {
    //   console.log('');
    // }
    toSendInfo(data);
  }
  // 1.信息组装
  function signalrService(
    content: any,
    identity: any,
    type: any,
    isSend2Other = true,
    isRobot = false
  ) {
    console.log('identity', identity);
    if (sendInfo || content) {
      const createDate = nowTime();
      // 时间戳
      const timeStmp = +new Date();
      // 信息模板
      const infoTemplate = {
        SendId: sender.id,
        ReviceId: isRobot ? 0 : revicer.id,
        Content: content,
        Identity: identity,
        Type: type,
        OutTradeNo: revicer.OutTradeNo,
        // 在线或者不在线，1不在线，0在线
        State: isRobot || !sender.onlineState ? 1 : 0,
        timeStmp: timeStmp,
        socketId: revicer.socketId,
        CreateDateUtc: createDate,
        Title: null,
        Description: null,
        Label: null,
        Thumbnail: null,
        NoSend: true,
      };
      toSendInfo(infoTemplate);
      if (isSend2Other) {
        sendMsg(infoTemplate);
      }
      setSendInfo('');
      // sendState.value = isRobot || !sender.onlineState ? true : false;
      // 如果type 不是表情
      // if (type !== 2) {
      //   setSendInfo = '';
      // }
      toBottom(100, chatRef);
    }
  }
  function joinSuccess() {
    // 当前用户接收加入提示信息
    mySocket.on('joinSuccess', (data: any) => {
      // sender.onlineState = true;
      setRevicer({
        ...revicer,
        id: data.ReviceId,
        name: data.ReviceName,
        OutTradeNo: data.ReviceOutTradeNo,
      });
    });
  }
  function joinError() {
    // 呼叫客服
    mySocket.on('joinError', (data: string) => {
      // console.log();
    });
  }
  // 2.发送信息
  function sendMsg(data: any) {
    mySocket.emit('sendMsg', data);
    // sendFailed(data);
  }
  // 发送消息模板
  function toSendInfo(data: any) {
    /*
     * identity:【0：机器人】【1：客服】 【2：顾客】
     * type:【0:文本】 【1:图片】 【2:表情】 【3:商品卡片/订单卡片】
     * */
    setConversition((pre) => [
      ...pre,
      {
        // 发送者 Id
        SendId: data.SendId,
        // 接收方id
        ReviceId: data.ReviceId,
        // 发送内容
        Content: data.Content,
        // 身份识别 【0：机器人】【1：客服】 【2：顾客】
        Identity: data.Identity,
        // 信息类型 ：0 文本，1 图片，2 表情，3 商品卡片/订单卡片，4 机器人回复
        Type: data.Type,
        // 信息发送状态
        State: data.State,
        // 发送者时间戳
        timeStmp: data.timeStmp,
        // 发送者 socketId
        socketId: data.socketId,
        // 	发送信息时间
        CreateDateUtc: data.CreateDate,
        // 推送卡片-标题
        Title: data.Title,
        // 推送卡片-描述
        Description: data.Description,
        // 推送卡片-标签
        Label: data.Label,
        // 推送卡片-图片
        Thumbnail: data.Thumbnail,
        // 卡片标题
        NoSend: true,
      },
    ]);
    toBottom(100, chatRef);
  }
  // mySocket.on('joinSuccess', (data) => {
  //   console.log(888, data);
  // });
  // 加入会话;
  function joinChat() {
    console.log('joinChat1', sender);
    // 呼叫客服
    mySocket.emit('joinChat', {
      SendId: sender.id,
      ReviceId: revicer.id,
      SendName: sender.name,
      ReviceName: revicer.name,
      IsService: sender.isService,
      NoCode: +new Date(),
    });
  }

  return (
    <div styleName="servies-box">
      <Header
        title={`在线客服`}
        onBack={back}
        style={{
          background: '#fff',
          color: '#333',
        }}
        type={1}
      />
      {getToken() ? (
        <div>
          {!isService ? (
            <ChatBox
              ref={chatRef}
              conversition={conversition}
              sender={sender}
              revicer={revicer}
            ></ChatBox>
          ) : (
            <ServiceChatBox
              ref={chatRef}
              conversition={conversition}
              sender={sender}
              revicer={revicer}
            ></ServiceChatBox>
          )}

          <SocketContext.Provider value={mySocket}>
            <Bottom
              setConversition={setConversition}
              conversition={conversition}
              signalrService={signalrService}
              sendInfo={sendInfo}
              setSendInfo={setSendInfo}
            ></Bottom>
          </SocketContext.Provider>
        </div>
      ) : (
        <NoLogin></NoLogin>
      )}

      {/*
      <div styleName="Servies-box-con">
        <Nav
          date={departDate}
          isPrevDisabled={isPrevDisabled}
          isNextDisabled={isNextDisabled}
          prev={prev}
          next={next}
        />
        <List list={trains} />
      </div>
      <Bottom highSpeed={highSpeed}></Bottom> */}
    </div>
  );
}

export default memo(Services);
